package com.liu.network.netty;

public class NettyServerUtils {
	private final static int NETTY_SERVER_PORT = 9998;

	public static void main(String[] args) {
		NettyServerUtils server = new NettyServerUtils();
		server.bind(NETTY_SERVER_PORT);
	}

	public void bind(int port) {
		// 接受新连接线程组，主要负责创建新连接
		NioEventLoopGroup boos = new NioEventLoopGroup();
		// 负责读取数据的线程，主要用于读取数据以及业务逻辑处理
		NioEventLoopGroup worker = new NioEventLoopGroup();

		// ServerBootstrap NIO服务端启动类
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		serverBootstrap.group(boos, worker);
		// 配置 Channel
		serverBootstrap.channel(NioServerSocketChannel.class);
		serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
		serverBootstrap.childHandler(new ServerIniterHandler());
		// BACKLOG用于构造服务端套接字ServerSocket对象，初始化服务端可连接队列。
		// 标识当服务器请求处理线程全满时，用于临时存放已完成三次握手的请求的队列的最大长度
		// 是否启用心跳保活机制
		serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
		try {
			// 绑定端口,同步等待绑定操作成功
			ChannelFuture channelFactory = serverBootstrap.bind(port).sync();
			// 服务器关闭监听
			channelFactory.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
			System.exit(1);
		} finally {
			// 优雅退出,释放线程池资源
			boos.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
	/**
	 * 初始化处理器
	 */
	private class ServerIniterHandler extends ChannelInitializer<SocketChannel> {
		@Override
		protected void initChannel(SocketChannel socketChannel) throws Exception {
			//每个通道都有自己的管道，并且在创建新通道时自动创建管道
			ChannelPipeline pipeline = socketChannel.pipeline();
			//编码管道处理器
			//数据格式一： key;value/r/n
//	        pipeline.addLast("LineBasedFrameDecoder", new LineBasedFrameDecoder(1024));
//	        pipeline.addLast("StringDecoder", new StringDecoder());
//	        pipeline.addLast("decode", new NettyServerHandler());
			//数据格式二： length keyLen valueLen key value
//	        pipeline.addLast("LengthFieldBasedFrameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 0));
			pipeline.addLast("decode", new NettyServerHandler1());
		}
	}
}
